/**
 * Created by yoyoyk on 2017/6/26.
 */
import React,{PropTypes} from "react";
import {hashHistory,Router} from 'react-router';
import  Relay from 'react-relay';
import {Button,getQiniuToken} from 'fly';
import {message} from 'antd';

import Context from './context';
import Process from './components/Logic_Process';
import ApprovalSet from './components/Logic_ApprovalSet';
import saveSampleCreate from "./mutaion/saveSampleCreate";

import './style.css';

export default class A extends React.Component {
    static defaultProps = {
        prefixCls : "create_proofing"
    };

    static childContextTypes = {
        process: PropTypes.object,
        setting:PropTypes.object,
        footer:PropTypes.object,
    };

    state = {
        token:"",
        createBtnDis:false
    };

    componentWillMount() {

        const propState = this.props.location;

        // 获取上传图片所需的token
        getQiniuToken((res) => {
            if (res.errorCode == 0) {
                this.setState({token: res.qiniutoken})
            }
        });

        if (propState && propState.state) {
            const record = this.record = Object.assign({}, propState.state.record);

            // console.log(this.record);
            if (record.orderType !== 1) {
                hashHistory.push({
                    pathname: '/OrderIndex', state: {
                        'record': record,
                        defaultActiveKey: 10,
                        showProofing: 1
                    }
                })
            }
        }else{
            message.info("请按规则进入");
            this.errorRender = () => <div className=""> 空 </div>
        }
    }

    // 分发Context文案及配置
    getChildContext(){return Context};

    ApprovalSetTest(ApprovalSetState){
        const {fileList,replaySetting,noteValue,partA,partAName} = ApprovalSetState;

        const reg = /[^\s]/;

        for(let i =0,j=fileList.length; i<j; i++){
            if(fileList[i].status !== "done"){
                message.info("请等待文件上传完毕");
                return false;
            }
        }

        if(noteValue.length > 100 && reg.test(noteValue)){ message.error("备注格式有误"); return false; }

        if( !reg.test(partAName) ){ message.error("请检查甲方公司名称"); return false; }

        return {
            fileListJson:JSON.stringify(fileList),
            approveType:replaySetting,
            mark:noteValue,
            partA:partA,
            partAName:partAName
        }
    };

    ProcessTest(ProcessState) {
        let activeList = JSON.parse(JSON.stringify(ProcessState.activeList));
        const NECESSARY = ["deliveryDate", "sampleId"];  //必需参数
        if(activeList.length <=0){ message.error("请选择打样流程"); return false; }

        for(let i=0; i<activeList.length; i++){
            const item = activeList[i];
            if (item[NECESSARY[0]] === null) {
                message.error("请选择发货日期");
                return false;
            }else if (item[NECESSARY[1]] === null) {
                message.error("数据出错，请联系系统管理员");
                return false;
            }else if (item.sampleId === 4 && (!item.size || item.size.length === 0)) {
                message.error("请设置尺码样");
                return false
            }
        }
        return JSON.stringify(activeList);
    };

    // 统一验证数据格式
    create = ()=>{
        let {Process,ApprovalSet} = this.refs;

        if(Process && ApprovalSet){
            Process = Process.state;
            ApprovalSet = ApprovalSet.state;
        }

        let ProcessData = this.ProcessTest(Process);

        if(!ProcessData){ return; }

        let ApprovalSetData = this.ApprovalSetTest(ApprovalSet);

        if(!ApprovalSetData){ return; }

        this.setState({createBtnDis:true});

        if(this.record){
            const r = this.record;
            const fromObj = {
                orderId:r.oid,
                username:sessionStorage.getItem("username"),
                enterpriseId:sessionStorage.getItem("enterpriseId"),
                enterpriseName:sessionStorage.getItem("enterpriseName"),

                approveType:ApprovalSetData.approveType,  //单选
                partA:ApprovalSetData.partA,
                partAName:ApprovalSetData.partAName,
                mark:ApprovalSetData.mark,                //备注
                fileJSON:ApprovalSetData.fileListJson,    //文件
                dateJson:ProcessData         //JSON
            };

            this.createHttpRequest(fromObj,(res)=>{
                res = res.saveSampleCreate.responseData;
                setTimeout(()=>{
                    this.setState({createBtnDis:false});
                    if(res.errorCode === "0"){
                        message.success("创建成功,正在跳转打样进度页");
                        setTimeout(()=>{
                            hashHistory.push({pathname:'/OrderIndex',state:{
                                'record':this.record,
                                defaultActiveKey: 10,
                                showProofing:1
                            }});
                        });
                    }else{
                        message.error("创建失败,正在返回订单列表");
                        setTimeout(()=>{
                            hashHistory.push({pathname:'/ordersaleyes'});
                        });
                    }
                },1000);
            });
        }
    };

    createHttpRequest(obj,callback){
        Relay.Store.commitUpdate(
            new saveSampleCreate({...obj}),
            {
                onFailure: (e) => {},
                onSuccess: (res) => {callback(res)}
            }
        )
    }

    render() {
        const props = Object.assign({},this.props);

        const {token,createBtnDis} = this.state;

        const clsName = props.prefixCls;

        return this.errorRender ? this.errorRender() :
            <div className={clsName}>
                <section key="process">
                    <Process ref="Process" key="process"/>
                </section>

                <ApprovalSet ref="ApprovalSet" record={this.record} key="approvalset" token={token}/>

                <footer  key="footer">
                    <Button onClick={this.create} disabled={createBtnDis}>
                        创建
                    </Button>
                </footer>
            </div>
    }
}